﻿using ProtoBuf;
using System.IO;

namespace ThresholdAssistant.Tools
{
    /// <summary>
    /// ProtoBuf序列化
    /// </summary>
    public class ProtoBufConvert
    {
        /// <summary>
        /// 对象序列化成二进制
        /// </summary>
        /// <typeparam name="T">序列化对象类型</typeparam>
        /// <param name="value">对象的值</param>
        /// <returns></returns>
        public static byte[] SerializeObject<T>(T value)
        {
            using MemoryStream ms = new MemoryStream();
            Serializer.SerializeWithLengthPrefix(ms, value, PrefixStyle.Base128);
            return ms.ToArray();
        }

        /// <summary>
        /// 二进制对象反序列化成对象
        /// </summary>
        /// <typeparam name="T">反序列化对象类型</typeparam>
        /// <param name="bytes">二进制对象数组</param>
        /// <returns></returns>
        public static T DeserializeObject<T>(byte[] bytes)
        {
            using MemoryStream ms = new MemoryStream(bytes);
            return Serializer.DeserializeWithLengthPrefix<T>(ms, PrefixStyle.Base128);
        }
    }
}